#include "hi_pwm.h"
#include "hi_errno.h"
#include "kp_pwm.h"


unsigned int PwmInit(unsigned int clock, unsigned int port)
{
    /*if (hi_pwm_set_clock((hi_pwm_clk_source)clock) != HI_ERR_SUCCESS) {
        return HI_ERR_FAILURE;
    }
    return hi_pwm_init((hi_pwm_port)port);*/
    if (hi_pwm_init((hi_pwm_port)port) != HI_ERR_SUCCESS) {
        return HI_ERR_FAILURE;
    }
    return hi_pwm_set_clock((hi_pwm_clk_source)clock);
}

unsigned int PwmDeinit(unsigned int port)
{
    return hi_pwm_deinit((hi_pwm_port)port);
}

unsigned int PwmStart(unsigned int port, unsigned int clock, unsigned short duty, unsigned int freq)
{
    unsigned short hiDuty;
    unsigned short hiFreq;

    if ((freq == 0) || (duty >= PWM_DUTY_MAX) || (duty == PWM_DUTY_MIN)) {
		printf("%s %s %d HI_ERR_FAILURE \r\n", __FILE__, __FUNCTION__, __LINE__);
        return HI_ERR_FAILURE;
    }

    if ((clock / freq) > PWM_SHORT_MAX) {
		printf("%s %s %d HI_ERR_FAILURE \r\n", __FILE__, __FUNCTION__, __LINE__);
        return HI_ERR_FAILURE;
    }

    hiFreq = (unsigned short)(clock / freq);
    hiDuty = (duty * hiFreq) / PWM_DUTY_MAX;

    return hi_pwm_start((hi_pwm_port)port, hiDuty, hiFreq);
}

unsigned int PwmStop(unsigned int port)
{
    return hi_pwm_stop((hi_pwm_port)port);
}

